// pages/result/result.js
const app = getApp();
var com = require('../../utils/common.js');
var linkText = com.linkText;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}, //个人信息
    hasUserInfo: false,
    movieNum: '0', //电影数量
    money: '0', //贡献金额
    percentage: '0',  //超越用户百分比
    movieData: '', //电影列表
    goodMovie: '', // 高分电影数量
    beShow: false
  },
  // 事件函数
  backChoose: function(){
    wx.navigateBack({ changed: true });//返回上一页  
  },
  //获取临时路径
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'labelCanvas',
      success: (res) => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        });
      }
    })
  },
  // 福利
  toWelfare: function(){
    wx.navigateTo({
      url: '../welfare/welfare'
    });
  },
  //保存至相册
  saveImageToPhotosAlbum: function () {
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        this.setData({
          beShow: true
        });
        setTimeout(function(){
          this.setData({
            beShow: false
          });
        }.bind(this), 1500);
        
      },
      fail: (err) => {
        
      }
    })
  },
  // canvas
  canvasIdErrorCallback: function (e) {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    // 计算一共看了几部电影
    var chooseMovie = [], choose = e.chooseImgUrl, imgUrlArr = [];
    var chooseScore = [], score = e.chooseScore, scoreArr = [];
    var scoreVal = [], goodMovieNum = 0, totalScore = 0;
    console.log(score)
    // 海报
    if(choose){
      chooseMovie = choose.split(",");
      this.setData({
        movieNum: chooseMovie.length,
        movieData: chooseMovie
      });
    }

    // 评分
    if (score){
      chooseScore = score.split(",");
      for(var i = 0; i < chooseScore.length; i ++){
        scoreVal.push(chooseScore[i].split("|")[0]);
        totalScore += Number(chooseScore[i].split("|")[0]);
        if (chooseScore[i].split("|")[0] > 6.0){
          goodMovieNum++;
        }
      }
      this.setData({
        goodMovie: goodMovieNum
      });
    }
    

    
    // 计算总价格
    var totalMoney = 0;
    for (var i = 0; i < chooseMovie.length; i ++){
      totalMoney += parseInt(Math.random() * 10 + 30);
    }
    this.setData({
      money: totalMoney
    });
    
    // 计算百分比
    var percentage = Math.ceil((Number(totalScore) / Number(this.data.movieNum)) * 10);
    if (percentage >= 99){
      percentage = 99;
    }
    this.setData({
      percentage: percentage
    });

    // 获取用户信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      }) 
    }

    wx.showShareMenu({
      withShareTicket: true
    });
  },
  getUserInfo: function (e) {
    console.log(e);
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: true
    });

    var getTempFilePath = this.getTempFilePath;
    // canvas
    var systemWidth = wx.getSystemInfoSync().screenWidth;
    var systemHeight = wx.getSystemInfoSync().screenHeight;
    var rpx = parseFloat(systemWidth / 750);  
    var context = wx.createCanvasContext('labelCanvas'); //定义画布
    context.save();
    context.drawImage('../../images/result_bg3.png', 0, 0, 750 * rpx, 1150 * rpx); //画背景
    context.setFontSize(30 * rpx);
    context.setFillStyle("#000");
    context.fillText("截至目前看了", 190 * rpx, 210 * rpx);

    var movieNum = this.data.movieNum + '';
    var movieNumWidth = movieNum.length * 40;
    var moneyStr = this.data.money + "";
    var goodMovieStr = this.data.goodMovie + "";
    var goodMovieWidth = goodMovieStr.length * 60;
    var yuan = "观影品味超越了";
    var yuanWidth = yuan.length * 30;
    var heightScore = "片，其中高分影片";
    var heightScoreWidth = heightScore.length * 30;

    context.fillText("部影", (movieNumWidth + 430) * rpx, 210 * rpx);
    context.fillText("片，其中高分影片", 180 * rpx, 270 * rpx);
    context.fillText("部", ((205 + heightScoreWidth + goodMovieWidth)) * rpx, 270 * rpx);
    context.fillText("观影品味超越了", ((140 + goodMovieWidth / 4)) * rpx, 330 * rpx);
    context.fillText("%的用户", ((195 + goodMovieWidth / 4) + yuanWidth + 60) * rpx, 330 * rpx);
    context.setFontSize(60 * rpx);
    context.setFillStyle("#fff");
    context.fillText(this.data.movieNum, 400 * rpx, 210 * rpx);
    context.fillText(this.data.goodMovie, ( 210 + heightScoreWidth) * rpx, 270 * rpx);
    context.fillText(this.data.percentage, ((140 + goodMovieWidth / 4) + yuanWidth + 20) * rpx, 330 * rpx);
    context.textAlign = 'center';
    context.fillText(this.data.userInfo.nickName + "", 375 * rpx, 140 * rpx);
    //画标签
    var movieData = this.data.movieData;
    context.restore();
    var textLength = 0, lineNum = 0, textLengthArr = [], lineArr = [];
    var line = 0;
    var otherData = [];
    var img = [];
    if (movieData.length == 0){
      context.draw(true, getTempFilePath); //画到 canvas的临时路径中，用来生成图片
    }else{
      for (var i = 0; i < movieData.length; i++) {
        // 下载电影图片
        var imgurl = movieData[i];
        var num = 0, iniLeft = 0, iniTop = 0, imgHeight = 0, imgWidth = 0, totalWidth = 0;;
        wx.downloadFile({
          url: imgurl, // 图片路径,
          success: function (res) {
            if (res.statusCode === 200) {
              img.push(res.tempFilePath);
              if (img.length === movieData.length) {
                if(img.length <= 15){
                  num = 4;
                  iniLeft = 71;
                  iniTop = 170;
                  imgHeight = 209;
                  imgWidth = 152;
                  totalWidth = 608;
                }else{
                  num = 6;
                  iniLeft = 75;
                  iniTop = 250;
                  imgHeight = 137;
                  imgWidth = 100;
                  totalWidth = 600;
                }
                for (var j = 0; j < img.length; j++) {
                  if (j % num == 0) {
                    line++;
                    textLength = 0;
                  }
                  textLength += imgWidth * rpx;
                  textLengthArr.push(textLength);
                  lineNum = parseInt(textLengthArr[j] / (totalWidth * rpx));
                  var left, top = (line * imgHeight + iniTop) * rpx;
                  if (j % num == 0) {
                    left = iniLeft * rpx;
                  } else {
                    left = iniLeft * rpx + textLengthArr[j - 1];
                  }
                  if (top <= 900 * rpx) {
                    context.beginPath();
                    context.drawImage(img[j], left, top, imgWidth * rpx, imgHeight * rpx); //画电影海报
                    context.closePath();
                  }
                }
                context.draw(true, getTempFilePath); //画到 canvas的临时路径中，用来生成图片
              }
            }
          },
          fail: function (err) {
            console.log(err)
          }
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var random = parseInt(Math.random() *4);
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: linkText[0],
        imageUrl: '../../images/forward.png',
        path: '/pages/index/index',
        success: function (e) {
          var shareTickets = res.shareTickets;
          if (shareTickets.length == 0) {
            return false;
          }
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function (res) {
              var encryptedData = res.encryptedData;
              var iv = res.iv;
            }
          });
          wx.showShareMenu({
            withShareTicket: true
          });
        },
      }
    }
    return {
      title: linkText[random],
      imageUrl: '../../images/forward.png',
      path: '/pages/index/index',
      success: function (e) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function (res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        });
        wx.showShareMenu({
          withShareTicket: true
        });
      },
    }
  }
})